import { getAllRoleList } from '@/apis/accessManagement/role'
import { getAvailableMenu } from '@/apis/accessManagement/menu'
import { getUserMenu } from '@/apis/accessManagement/menu'
import { editRole } from '@/apis/accessManagement/role'
import { addRole } from '@/apis/accessManagement/role'
import { switchForbidden } from '@/apis/accessManagement/role'
import { deleteRole } from '@/apis/accessManagement/role'
import { permitRole } from '@/apis/accessManagement/role'
import { editUserRole } from '@/apis/accessManagement/role'
import ExcelTable from '@/components/exportExcel'
import { ActionType, ProFormInstance } from '@ant-design/pro-components'
import { Button, Drawer, Modal, Form, Input, Flex, Tree, message, Switch, Spin } from 'antd'
import { useRef, useState, useEffect } from 'react'
import type { TreeProps } from 'antd'
const RoleManange: React.FC = () => {
  useRef<ActionType>()
  useRef<ProFormInstance>()
  const [tableItem, setTableItem] = useState()
  const [form] = Form.useForm()
  const actionRef = useRef()
  const [messageApi, contextHolder] = message.useMessage()
  const [valueEnum, setValueEnum] = useState({})
  const [loading, setLoading] = useState(false)
  const [roleId, setRoleId] = useState(null)
  const [drawerMode, setDrawerMode] = useState(null)
  const [menuData, setMenuData] = useState([])
  const [userMenuStatus, setUserMenuStatus] = useState(false)

  const [authorizationDrawer, setAuthorizationDrawer] = useState(false)
  const [addDrawer, setAddDrawer] = useState(false)
  const [titleDrawer, setTitleDrawer] = useState('新增')
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([])
  const [checkedKeys, setCheckedKeys] = useState<any>({})
  const [selectedKeys, setSelectedKeys] = useState<any>([])
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true)

  const onExpand: TreeProps['onExpand'] = expandedKeysValue => {
    setExpandedKeys(expandedKeysValue)
    setAutoExpandParent(false)
  }
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue, info) => {
    setCheckedKeys(checkedKeysValue as React.Key[])
  }
  const onSelect = (selectedKeysValue: any, { node }: { node: any }) => {
    const { checked, halfChecked } = checkedKeys

    // 计算新的 checkedKeys
    const newChecked = checked.includes(node.key)
      ? checked.filter((key: any) => key !== node.key) // 取消选中
      : [...checked, node.key] // 添加选中

    // 更新 checkedKeys，只修改 checked，不影响 halfChecked
    setCheckedKeys({ checked: newChecked, halfChecked })

    // 更新 selectedKeys（用于 UI 高亮）
    setSelectedKeys(selectedKeysValue)
  }

  function showAddEditDrawer(title: string, item: any, mode: any) {
    setTitleDrawer(title)
    setAddDrawer(true)
    if (mode === 2) {
      setRoleId(item.roleId)
      form.setFieldsValue({ roleName: item.roleName })
      form.setFieldsValue({ roleCode: item.roleCode })
      // form.setFieldsValue({ status: item.status === 1?true:false })
      form.setFieldsValue({ desc: item.desc })
    }
    setDrawerMode(mode)
    // console.log(item)
    // setTableItem(item)
  }

  function showAuthorizationDrawer(item: any) {
    setRoleId(item.roleId)
    setCheckedKeys({})
    searchUserMenu(item.roleId)
    // setTableItem(item)
    setAuthorizationDrawer(true)
    searchMenu()
  }

  function onCloseDrawer() {
    form.resetFields()
    setAddDrawer(false)
    setAuthorizationDrawer(false)
  }

  // 查询用户授权状态
  const searchUserMenu = async (roleId: any) => {
    setLoading(true)
    try {
      const response = await getUserMenu({
        roleId: roleId
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          // setUserMenu(response.data.menuIds)
          setCheckedKeys({ checked: response.data.menuIds as React.Key[], halfChecked: [] })
        } else {
          message.error(`授权提交失败: ${response?.errMsg || '未知错误'}`)
        }
        // console.log(Object.keys(response.data).length)
        if (Object.keys(response.data).length > 0) {
          setUserMenuStatus(true)
        } else {
          setUserMenuStatus(false)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  // 提交新增授权
  const subAuth = async () => {
    setLoading(true)
    try {
      const response = await permitRole({
        roleId: roleId,
        menuIds: checkedKeys.checked
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('授权成功')
          setAuthorizationDrawer(false)
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`授权提交失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  // 提交修改授权
  const subEditUserRole = async () => {
    setLoading(true)
    try {
      const response = await editUserRole({
        roleId: roleId,
        menuIds: checkedKeys.checked
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('修改授权成功')
          setAuthorizationDrawer(false)
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`修改授权提交失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  // 提交修改角色
  const subUpdate = async () => {
    // setLoading(true)
    try {
      const response = await editRole({
        roleName: form.getFieldValue('roleName'),
        roleCode: form.getFieldValue('roleCode'),
        status: null,
        desc: form.getFieldValue('desc'),
        roleId: roleId
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('角色修改成功')
          form.resetFields()
          setAddDrawer(false)
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      // setLoading(false)
    }
  }

  // 提交新增角色
  const subAdd = async () => {
    try {
      const response = await addRole({
        roleName: form.getFieldValue('roleName'),
        roleCode: form.getFieldValue('roleCode'),
        status: form.getFieldValue('status') === true ? 1 : 2,
        desc: form.getFieldValue('desc')
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('角色修改成功')
          form.resetFields()
          setAddDrawer(false)
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
    }
  }

  // 禁用/解禁角色
  const changeForbidden = async (record: any) => {
    setLoading(true)
    try {
      const response = await switchForbidden({
        roleId: record.roleId,
        status: record.status === 1 ? 2 : 1
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('提交成功')
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交数据失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  // 删除角色
  const subDelete = async (record: any) => {
    setLoading(true)
    try {
      const response = await deleteRole({
        roleId: record.roleId
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('删除成功')
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交数据失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  // 查询授权菜单
  const searchMenu = async () => {
    try {
      const response = await getAvailableMenu({})
      if (response || response.data) {
        if (response?.errCode === 0) {
          const buildTree = (menuInfo: any) => {
            // 创建一个 Map，用于快速查找父节点
            const menuMap = new Map()
            // 遍历所有菜单，先将每个节点注册到 map 中
            menuInfo.forEach((item: any) => {
              menuMap.set(item.menuId, { ...item, children: [] })
            })
            // 构建树形结构
            const tree: any = []
            menuInfo.forEach((item: any) => {
              if (item.menuParentId && menuMap.has(item.menuParentId)) {
                // 如果存在父节点，将其添加到父节点的 children 数组中
                menuMap.get(item.menuParentId).children.push(menuMap.get(item.menuId))
              } else {
                // 如果没有父节点，添加到根节点
                tree.push(menuMap.get(item.menuId))
              }
            })
            return tree
          }
          // console.log(buildTree(response.data.menuInfo))
          setMenuData(buildTree(response.data.menuInfo))
        } else {
          message.error(`查询数据失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    }
  }
  console.log(checkedKeys, 'checkedKeys')

  return (
    <>
      {contextHolder}
      <Spin spinning={loading} fullscreen size="large" />
      <ExcelTable
        actionRef={actionRef}
        requestFn={async params => {
          const {
            pageNum,
            pageSize,
            roleName = '',
            roleCode,
            status = 0,
            changeBy = '',
            startTime = '',
            endTime = '',
            ...newParams
          } = params // 处理所需参数名
          const data = await getAllRoleList({
            ...newParams,
            pagination: { pageNumber: pageNum, showNumber: pageSize },
            roleName: roleName,
            roleCode: roleCode,
            status: parseInt(status),
            changeBy: changeBy,
            startTime: startTime,
            endTime: endTime
          })
          return data
        }}
        rowSelection={false}
        toolBarRenderFn={() => [
          <Button key="add" onClick={() => showAddEditDrawer('新增', {}, 1)}>
            新增
          </Button>
        ]}
        columns={[
          {
            title: '角色名称',
            dataIndex: 'roleName',
            hideInTable: true
            // valueType: 'select',
            // valueEnum
          },
          {
            title: '状态',
            dataIndex: 'status',
            hideInTable: true,
            valueType: 'select',
            valueEnum: {
              0: '全部',
              1: '正常',
              2: '禁用'
            }
          },
          //   {
          //     title: '操作时间',
          //     dataIndex: 'keyword7',
          //     valueType: 'dateRange',
          //     hideInTable: true
          //   },
          /** table */
          {
            title: '序号',
            valueType: 'index',
            hideInSearch: true
          },
          {
            title: '角色名称',
            dataIndex: 'roleName',
            hideInSearch: true
          },
          {
            title: '角色标识',
            dataIndex: 'roleCode',
            hideInSearch: true
          },
          {
            title: '角色描述',
            dataIndex: 'desc',
            hideInSearch: true
          },
          {
            title: '状态',
            dataIndex: 'status',
            hideInSearch: true,
            valueEnum: {
              0: '全部',
              1: '正常',
              2: '禁用'
            },
            render: (_, record) => (
              <span
                style={{
                  color: record.status === 1 ? 'green' : record.status === 2 ? 'red' : 'gray'
                }}
              >
                {record.status === 1 ? '正常' : record.status === 2 ? '禁用' : '暂无数据'}
              </span>
            )
          },
          {
            title: '操作时间',
            dataIndex: 'updateTime',
            hideInSearch: true,
            valueType: 'dateTime'
          },
          {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_, record) => [
              <a key="update" onClick={() => showAddEditDrawer('修改角色信息', record, 2)}>
                角色修改
              </a>,
              <a key="authorization" onClick={() => showAuthorizationDrawer(record)}>
                授权
              </a>,
              <a
                key="disabled"
                onClick={() => {
                  const text = record.status === 1 ? '禁用' : '解禁'
                  setRoleId(record.roleId)
                  Modal.warning({
                    title: '提示',
                    content: `确定${text}该角色吗?`,
                    okText: '确定',
                    okCancel: true,
                    onOk() {
                      changeForbidden(record)
                    }
                  })
                }}
              >
                {record.status === 1 ? '禁用' : '解禁'}
              </a>,
              <a
                key="delete"
                onClick={() => {
                  Modal.warning({
                    title: '提示',
                    content: '确定删除该角色吗?',
                    okText: '确定',
                    okCancel: true,
                    onOk() {
                      subDelete(record)
                    }
                  })
                }}
              >
                删除
              </a>
            ]
          }
        ]}
      />
      <Drawer title={titleDrawer} onClose={onCloseDrawer} open={addDrawer}>
        <Form form={form} onFinish={drawerMode === 1 ? subAdd : subUpdate}>
          <Form.Item
            label="角色名称"
            name="roleName"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" maxLength={50} />
          </Form.Item>
          <Form.Item
            label="角色标识"
            name="roleCode"
            rules={[{ required: true, message: '请输入角色标识' }]}
          >
            <Input placeholder="请输入角色标识" maxLength={50} />
          </Form.Item>
          {drawerMode === 1 && (
            <Form.Item name="status" label="状态" valuePropName="checked">
              <Switch checkedChildren="正常" unCheckedChildren="禁用" />
            </Form.Item>
          )}
          <Form.Item label="角色描述" name="desc">
            <Input.TextArea
              rows={4}
              maxLength={200}
              placeholder="请输入您的角色描述，最多不超过200字。"
            />
          </Form.Item>
          <Form.Item>
            <Flex justify="center" align="center">
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={onCloseDrawer}>
                返回
              </Button>
            </Flex>
          </Form.Item>
        </Form>
      </Drawer>
      <Drawer title="授权" onClose={onCloseDrawer} open={authorizationDrawer}>
        <Spin spinning={loading}>
          <Tree
            checkable
            selectable
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onCheck={onCheck}
            checkStrictly
            // onCheck={(checkedKeys) => {setCheckedKeys(checkedKeys.checked)}}
            checkedKeys={checkedKeys}
            onSelect={onSelect}
            selectedKeys={selectedKeys}
            treeData={menuData}
            fieldNames={{
              title: 'menuName', // 显示路径作为标题
              key: 'menuId', // 使用 menuId 作为 key
              children: 'children' // 子节点字段
            }}
          />
          <Flex justify="center" align="center" style={{ marginTop: '20px' }}>
            <Button
              type="primary"
              onClick={() => {
                userMenuStatus === true ? subEditUserRole() : subAuth()
              }}
            >
              提交
            </Button>
            <Button style={{ marginLeft: 10 }} onClick={onCloseDrawer}>
              返回
            </Button>
          </Flex>
        </Spin>
      </Drawer>
    </>
  )
}

export default RoleManange
